﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using Newtonsoft.Json;

namespace SlamCms.Common
{
	public static class Generic
	{
		public static bool In<T>(this T source, IEnumerable<T> list)
		{
			if (source == null) throw new ArgumentNullException("source");
			return list.Contains(source);
		}

		public static bool In<T>(this T source, params T[] list)
		{
			if (source == null) throw new ArgumentNullException("source");
			return list.Contains(source);
		}

		public static int Times(this int instance, Action<int> action)
		{
			for (var i = 0; i < instance; i++)
				action(i);
			return instance;
		}

		public static IList<T> Clone<T>(this IList<T> listToClone) where T : ICloneable
		{
			return listToClone.Select(item => (T)item.Clone()).ToList();
		}

		public static T DeepClone<T>(this T obj)
		{
			using (var ms = new MemoryStream())
			{
				var formatter = new BinaryFormatter();
				formatter.Serialize(ms, obj);
				ms.Position = 0;

				return (T)formatter.Deserialize(ms);
			}
		}

		public static IEnumerable<T> Use<T>(this T obj) where T : IDisposable
		{
			try
			{
				yield return obj;
			}
			finally
			{
				if (obj != null)
					obj.Dispose();
			}
		}

		public static string ToJson(this object instance)
		{
			return JsonConvert.SerializeObject(instance);
		}
	}
}
